//
//  BFileManagerTool.m
//  Bullet
//
//  Created by  on 2019/9/17.
//  Copyright © 2019 . All rights reserved.
//

#import "BFileManagerTool.h"
#import "BConst.h"
#include <sys/param.h>
#include <sys/mount.h>


@implementation BFileManagerTool

#pragma mark - path


- (NSString *)documentPath{
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return pathArray[0];
}

- (NSString *)cachePath{
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return pathArray[0];
}

- (NSString *)fileSaveCachePath{
    return [[self cachePath] stringByAppendingPathComponent:@"BulletIOS"];
}

- (NSString *)pathWithGroup:(NSString *)groupName{
    NSString *groupPath = [[self fileSaveCachePath] stringByAppendingPathComponent:groupName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:groupPath isDirectory:&isDir];
    if(!(isDirExist && isDir))
    {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:groupPath withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
//            BLog(@"Create Group Directory Failed.%@",groupPath);
        }
    }
    return groupPath;
}

- (void)createPath:(NSString *)createP{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:createP isDirectory:&isDir];
    if(!(isDirExist && isDir))
    {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:createP withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
//            BLog(@"Create Group Directory Failed.%@",createP);
        }
    }
}

- (NSString *)folderNameFormUrl:(NSString *)urlStr{
    urlStr = [urlStr stringByReplacingOccurrencesOfString:@"." withString:@""];
    urlStr = [urlStr stringByReplacingOccurrencesOfString:@"/" withString:@""];
    urlStr = [urlStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    urlStr = [urlStr stringByReplacingOccurrencesOfString:@":" withString:@""];
    return urlStr;
}

- (NSString *)videoCachePathForUrl:(NSString *)urlStr{
    return [self videoCachePathForUrl:urlStr preload:NO];
}

- (NSString *)videoCachePathForUrl:(NSString *)urlStr preload:(BOOL)preload{
    NSArray * strArr = [urlStr componentsSeparatedByString:@"?"];
    NSString *folderUrl = [[self fileSaveCachePath] stringByAppendingPathComponent:[self folderNameFormUrl:strArr[0]]];
    
    NSString *cachePath = [folderUrl stringByAppendingPathComponent:urlStr.lastPathComponent];
    if([cachePath containsString:@".m3u8"] && preload){
        cachePath = [cachePath stringByReplacingOccurrencesOfString:cachePath.lastPathComponent withString:[NSString stringWithFormat:@"Pre%@",cachePath.lastPathComponent]];
    }
    
    return cachePath;
}

- (BOOL)fileIsExists:(NSString *)path{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        return YES;
    }
    return NO;
}

- (NSDate *)getFolderCreateDate:(NSString *)folderPath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager attributesOfItemAtPath:folderPath error:nil].fileCreationDate;
}

- (NSString *)getPathWithFileName:(NSString *)imageName type:(NSString *)groupName{
    NSString *appIconP = [self pathWithGroup:groupName];
    NSString *savePath = [appIconP stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",imageName]];
    return savePath;
}

#pragma mark - save
- (void)saveFileWithUrl:(NSString *)path group:(NSString *)group name:(NSString *)name{
    NSString *savePath = [self getPathWithFileName:name type:group];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:savePath]){
        return;
    }
    NSError *error = nil;
    [fileManager copyItemAtPath:path toPath:savePath error:&error];
    if(error){
//        BLog(@"save file failed,error is %@,o path is %@,c path is %@",error,path,savePath);
    }
}

#pragma mark - image

- (NSString *)recordingVideoPath{
    return [[BFileManagerTool tool] getPathWithFileName:@"BUserRecordVideo.mov" type:@"BUserRecordVideo"];
}

- (NSString *)recordingVideoMP4Path{
    return [[BFileManagerTool tool] getPathWithFileName:@"BUserRecordVideo.mp4" type:@"BUserRecordVideo"];
}

- (NSString *)recordingVideoCoverPath{
    return [[BFileManagerTool tool] getPathWithFileName:@"BUserRecordVideo.jpg" type:@"BUserRecordVideo"];
}

- (NSString *)recordingPreVideoMP4Path{
    return [[BFileManagerTool tool] getPathWithFileName:@"PreBUserRecordVideo.mp4" type:@"BUserRecordVideo"];
}

- (NSString *)recordingTmpPicDirector{
    NSString *imgStr = [[self recordingVideoPath] stringByReplacingOccurrencesOfString:[self recordingVideoPath].lastPathComponent withString:@""];
    imgStr = [imgStr stringByAppendingString:@"Tmp/"];
    [[BFileManagerTool tool] createPath:imgStr];
    return imgStr;
}

- (NSString *)recordingVideoPixImgPath:(CGFloat)duration{
    return [[self recordingTmpPicDirector] stringByAppendingFormat:@"%6f.jpg",duration];
}

- (UIImage *)recordingVideoImagFrame:(CGFloat)frame{
    NSString *tmpImageP = [self recordingVideoPixImgPath:frame];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    UIImage *returnImg = nil;
    if([fileManager fileExistsAtPath:tmpImageP]){
        returnImg = [[UIImage alloc] initWithContentsOfFile:tmpImageP];
    }
    return returnImg;
}

- (void)clearRecodingVideoPixTmpImg{
    [self deleteCacheFolder:[self recordingTmpPicDirector]];
}

- (void)clearRecordVideoPath{
    NSString *path  = [self pathWithGroup:@"BUserRecordVideo"];
    [self deleteCacheFolder:path];
}


#pragma mark - delete

- (void)deleteFileType:(NSString *)groupName name:(NSString *)name{
    NSString *path  = [self pathWithGroup:groupName];
    NSString *savePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",name]];
    [self deleteCacheFolder:savePath];
}

- (void)deleteCacheFolder:(NSString *)folderPath{
    NSFileManager *manager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *subPathArr = [manager contentsOfDirectoryAtPath:folderPath error:&error];
    if (error) {
//        BLog(@"Get subpaths array failed,error is : %@",error);
    }
    else
    {
        for (NSString *sub in subPathArr) {
            NSString *filePath = [folderPath stringByAppendingPathComponent:sub];
            if (![filePath containsString:@"/Caches/Snapshots"] &&
                ![filePath containsString:@"/Caches/default"] &&
                ![filePath containsString:@"com.apple.nsurlsessiond"]){
                [manager removeItemAtPath:filePath error:&error];
                if (error) {
//                    BLog(@"Remove item failed at path %@",filePath);
                }
                else
                {
//                    BLog(@"Remove item success at path %@",filePath);
                }
            }
        }
    }
}

- (void)deleteVideoCacheFolder:(void(^)(void))complete{
    [self deleteCacheFolder:[self fileSaveCachePath]];
    if(complete){
        complete();
    }
}

- (void)clearAllCache:(void(^)(void))complete{
    [self deleteCacheFolder:[self cachePath]];
    if(complete){
        complete();
    }
}

- (long long)videoSizeWithPath:(NSString *)path{
    NSInteger fileSize = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil].fileSize;
    return fileSize;
}

#pragma mark - size

- (unsigned long long)freeDiskSpaceInBytes{
//    struct statfs buf;
//    unsigned long long freeSpace = -1;
//    if (statfs("/var", &buf) >= 0) {
//        freeSpace = (unsigned long long)(buf.f_bsize * buf.f_bavail);
//    }
    struct statfs buf;
    unsigned long long freeSpace = -1;
    if (statfs("/var", &buf) >= 0) {
        freeSpace = (unsigned long long)(buf.f_bsize * buf.f_bavail);
    }
    return freeSpace;
    /*
     /// 总大小
     float totalsize = 0.0;
     /// 剩余大小
     float freesize = 0.0;
     /// 是否登录
     NSError *error = nil;
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
     if (dictionary)
     {
     NSNumber *_free = [dictionary objectForKey:NSFileSystemFreeSize];
     freesize = [_free unsignedLongLongValue]*1.0/(1024);
     
     NSNumber *_total = [dictionary objectForKey:NSFileSystemSize];
     totalsize = [_total unsignedLongLongValue]*1.0/(1024);
     } else
     {
     NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %ld", [error domain], (long)[error code]);
     }
     NSLog(@"totalsize = %.2f, freesize = %f",totalsize/1024/1024/1024, freesize/1024);
     */
    
//    return str;
}

- (unsigned long long)userCacheSize{
    return [self fileSize:[self cachePath]];
}

- (unsigned long long)fileSize:(NSString *)path{
    unsigned long long size = 0;
    NSFileManager *mgr = [NSFileManager defaultManager];
    NSDictionary *attrs = [mgr attributesOfItemAtPath:path error:nil];
    if ([attrs.fileType isEqualToString:NSFileTypeDirectory]) {
        NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:path];
        for (NSString *subpath in enumerator) {
            NSString *fullSubpath = [path stringByAppendingPathComponent:subpath];
            size += [mgr attributesOfItemAtPath:fullSubpath error:nil].fileSize;
        }
        
    }
    else
    {
        size = attrs.fileSize;
    }
    return size;
}

+ (instancetype)tool{
    static BFileManagerTool *fileManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        fileManager = [[BFileManagerTool alloc] init];
    });
    return fileManager;
}

@end
